﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CarbonExchange.Bll;
using System.Collections.Specialized;
using System.Web.UI.HtmlControls;

public partial class Templates_Audit_Section : LoggedInPageBase
{
    protected override void OnInit(EventArgs e)
    {
        //if(IsPostBack)
            //System.Threading.Thread.Sleep(1000);
        base.OnInit(e);
        listSections.ItemCreated += new EventHandler<ListViewItemEventArgs>(listSections_ItemCreated);
        listSections.ItemDataBound += new EventHandler<ListViewItemEventArgs>(listSections_ItemDataBound);
        listSections.ItemCommand += new EventHandler<ListViewCommandEventArgs>(listSections_ItemCommand);
    }

    protected override void OnPreRender(EventArgs e)
    {
        var pnlUpdate = listSections.Items[listSections.SelectedIndex].FindControl("pnlUpdate") as Panel;
        var item = new Telerik.Web.UI.AjaxSetting(pnlUpdate.ID);
        item.UpdatedControls.Add(new Telerik.Web.UI.AjaxUpdatedControl(pnlUpdate.ID, radLoadingPanel.ID));
        item.UpdatedControls.Add(new Telerik.Web.UI.AjaxUpdatedControl() { ControlID = pnlComplete.ID });
        ajaxManager1.AjaxSettings.Add(item);
        base.OnPreRender(e);
    }

    void listSections_ItemCommand(object sender, ListViewCommandEventArgs e)
    {
        if (e.CommandName == "SaveProgress" || e.CommandName == "Submit")
        {
            /*PlaceHolder phQuestions1 = e.Item.FindControl("phQuestions1") as PlaceHolder;
            PlaceHolder phQuestions2 = e.Item.FindControl("phQuestions2") as PlaceHolder;
            PlaceHolder phQuestions3 = e.Item.FindControl("phQuestions3") as PlaceHolder;
            if (phQuestions1 != null && phQuestions2 != null && phQuestions3 != null)
            {*/
            //PlaceHolder phQuestions = e.Item.FindControl("phQuestions") as PlaceHolder;
            var containerQuestions = e.Item.FindControl("containerQuestions") as CarbonExchange.WebControls.AuditQuestionContainer;
            if (containerQuestions != null)
            {
                bool completed = true;
                var tmp = containerQuestions.Controls.OfType<CarbonExchange.WebControls.AuditQuestionBase>();
                    //.Union(phQuestions2.Controls.OfType<CarbonExchange.WebControls.AuditQuestionBase>())
                    //.Union(phQuestions3.Controls.OfType<CarbonExchange.WebControls.AuditQuestionBase>());
                foreach (var item in tmp)
                {
                    var tmpCompleted = ((CarbonExchange.WebControls.AuditQuestionBase)item).Save();
                    if (!tmpCompleted)
                    {
                        completed = tmpCompleted;
                    }
                }

                var userSection = UserSections.Find(x => x.SectionId == this.Section.Id);
                if (userSection == null)
                {
                    userSection = new UserSection(Audit.Id, Section.Id);
                    UserSections.Add(userSection);
                }
                if (userSection != null)
                {
                    userSection.Completed = completed;
                    new UserSectionFactory().Save(userSection); 
                }
                //databind master to stats update
                //if (this.Master != null)
                //{
                //    this.Master.DataBind();
                //}
                //update completed display
                var lblCompleted = e.Item.FindControl("lblCompleted") as Label;
                if (lblCompleted != null)
                {
                    lblCompleted.Text = userSection.Completed ? "Completed" : "Incomplete";
                }

                var lblValue = e.Item.FindControl("lblValue") as Label;
                lblValue.Text = GetSectionValue(e.Item as ListViewDataItem);

                var savedMessage = e.Item.FindControl("savedMessage") as HtmlGenericControl;
                if (savedMessage != null)
                    savedMessage.Visible = true;

                SetCompletedPanelVisibilty();
            }
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        btnComplete.Click += new EventHandler(btnComplete_Click);
        if (!IsPostBack)
        {
            if (Audit == null)
            {
                AcmsContext.RedirectToUrl("~/MyCO2/CreateAudit.aspx", this);
                //Response.Redirect("Create.aspx", true);
            }

            int id = 0;
            if (Request.QueryString["Id"] != null)
            {
                try
                {
                    id = int.Parse(Request.QueryString["Id"]);
                }
                catch (FormatException)
                {
                }
            }
            CarbonExchange.Bll.SectionFactory factory = new CarbonExchange.Bll.SectionFactory();
            if (id > 0)
            {
                Section = factory.GetById(id);
            }
            else if (Sections.Count() > 0)
            {
                Section = Sections[0];
            }

            DataBind();
        }
    }

    void btnComplete_Click(object sender, EventArgs e)
    {
        AuditFactory factory = new AuditFactory();
        var tmp = factory.GetCurrentForUserId(User.Identity.User.Id);
        if (tmp != null)
        {
            tmp.Completed = true;
            factory.Save(tmp);
            AcmsContext.RedirectToUrl("~/MyCO2/MyCO2Statement.aspx", this);
        }
    }   

    void listSections_ItemDataBound(object sender, ListViewItemEventArgs e)
    {
        if (e.Item.ItemType == ListViewItemType.DataItem)
        {
/*            System.Web.UI.WebControls.ListViewDataItem item = e.Item as System.Web.UI.WebControls.ListViewDataItem;
            PlaceHolder phQuestions = e.Item.FindControl("phQuestions") as PlaceHolder;
            if (phQuestions != null)
            {
                Section dataItem = item.DataItem as Section;
                SiteQuestionFactory factory = new SiteQuestionFactory();
                var questions = factory.GetAllBySectionId(dataItem.Id, AcmsContext.SiteId).ToList();
                SetUpQuestions(questions, phQuestions);
            }
*/
            /*PlaceHolder phQuestions1 = e.Item.FindControl("phQuestions1") as PlaceHolder;
            PlaceHolder phQuestions2 = e.Item.FindControl("phQuestions2") as PlaceHolder;
            PlaceHolder phQuestions3 = e.Item.FindControl("phQuestions3") as PlaceHolder;
            if (phQuestions1 != null && phQuestions2 != null && phQuestions3 != null)
            {
                Section dataItem = item.DataItem as Section;
                SiteQuestionFactory factory = new SiteQuestionFactory();
                var questions = factory.GetAllBySectionId(dataItem.Id, AcmsContext.SiteId).ToList();
                SetUpQuestions(questions, phQuestions1, phQuestions2, phQuestions3);

            }*/
        }
        
    }

    //private void SetUpQuestions(List<SiteQuestion> questions, PlaceHolder phQuestions)//PlaceHolder phQuestions1, PlaceHolder phQuestions2, PlaceHolder phQuestions3)
    //{
//        var configs = questions.Select(x => new QuestionTextConfiguration(x));
//        UserControlPaths = configs.Select(x => x.UserControlPath).ToList();
///        var userControls = UserControlPaths.Select(x => Page.LoadControl(x) as CarbonExchange.WebControls.AuditQuestionBase);
//        var i = 0;
//        foreach (var item in userControls)
//        {
//            phQuestions.Controls.Add(item);
//            item.SetContext(configs.ElementAt(i), AcmsContext.SiteId, Audit);
//            item.DataBind();
//            i++;
//        }
        /*var itemsToRender = userControls.Select(x => x.GetActiveItemsCount()).Sum();
        int i = 0;
        int items = userControls.Count() / 3;
        int remainder = userControls.Count() % 3;
        int first = items + (remainder != 0 ? 1 : 0);
        int second = items + (remainder == 2 ? 1 : 0);
        foreach (var item in userControls)
        {
            item.SetContext(configs.ElementAt(i), AcmsContext.SiteId, Audit);
            if (i < first)
            {
                phQuestions1.Controls.Add(item);
            }
            else if (i < first + second)
            {
                phQuestions2.Controls.Add(item);
            }
            else
            {
                phQuestions3.Controls.Add(item);
            }
            item.DataBind();
            i++;
        }*/
//    }

    private List<string> UserControlPaths;

    void listSections_ItemCreated(object sender, ListViewItemEventArgs e)
    {
        if (e.Item.ItemType == ListViewItemType.DataItem)
        {
            /*var containerQuestions = e.Item.FindControl("containerQuestions") as Control;
            if (containerQuestions != null)
            {
                ajaxManager.AjaxSettings.AddAjaxSetting(containerQuestions, containerQuestions, radLoadingPanel);
            }*/
            /*if (((ListViewDataItem)e.Item).DisplayIndex == listSections.SelectedIndex)
            {
                ajaxManager.AjaxSettings.Add(new Telerik.Web.UI.AjaxSetting(e.Item.ID));
                ajaxManager.AjaxSettings[ajaxManager.AjaxSettings.Count - 1].UpdatedControls.Add(Telerik.Web.UI.AjaxUpdatedControl())'
            }*/
            //if (IsPostBack)
            //{
/*                PlaceHolder phQuestions = e.Item.FindControl("phQuestions") as PlaceHolder;
                if (phQuestions != null)
                {
                    var userControls = UserControlPaths.Select(x => Page.LoadControl(x) as CarbonExchange.WebControls.AuditQuestionBase);
                    foreach (var item in userControls)
                    {
                        phQuestions.Controls.Add(item);
                    }
                }
*/                /*PlaceHolder phQuestions1 = e.Item.FindControl("phQuestions1") as PlaceHolder;
                PlaceHolder phQuestions2 = e.Item.FindControl("phQuestions2") as PlaceHolder;
                PlaceHolder phQuestions3 = e.Item.FindControl("phQuestions3") as PlaceHolder;
                if (phQuestions1 != null && phQuestions2 != null && phQuestions3 != null)
                {
                    var userControls = UserControlPaths.Select(x => Page.LoadControl(x) as CarbonExchange.WebControls.AuditQuestionBase);
                    int items = userControls.Count() / 3;
                    int remainder = userControls.Count() % 3;
                    int first = items + (remainder != 0 ? 1 : 0);
                    int second = items + (remainder == 2 ? 1 : 0);
                    foreach (var item in userControls.Take(first))
                    {
                        phQuestions1.Controls.Add(item);
                    }
                    foreach (var item in userControls.Skip(first).Take(second))
                    {
                        phQuestions2.Controls.Add(item);
                    }
                    foreach (var item in userControls.Skip(first + second))
                    {
                        phQuestions3.Controls.Add(item);
                    }
                }*/
            //}
        }
    }

    public override void DataBind()
    {
        if (Audit != null)
        {
            lblTitle.Text = string.Format(" - {0:dd MMMM yyyy}", _Audit.EndDate);
        }
        if (Section != null)
        {
            //find the index and set the selected index
            listSections.SelectedIndex = Sections.FindIndex(x => x.Id == _SectionId);
            listSections.DataSource = Sections;
        }

        SetCompletedPanelVisibilty();
        base.DataBind();
    }

    private void SetCompletedPanelVisibilty()
    {
        //if all sections are complete then show complete button
        UserSectionFactory factory = new UserSectionFactory();
        var userSections = factory.GetAllByAuditId(Audit.Id).ToArray();
        if (userSections.Count() == Sections.Count && userSections.Where(x => !x.Completed).Count() == 0)
        {
            pnlComplete.Visible = true;
        }
        else
        {
            pnlComplete.Visible = false;
        }
    }

    private int? _SectionId;

    private CarbonExchange.Bll.Section _Section;
    protected CarbonExchange.Bll.Section Section
    {
        get 
        {
            if (_Section == null && _SectionId.HasValue)
            {
                CarbonExchange.Bll.SectionFactory factory = new CarbonExchange.Bll.SectionFactory();
                _Section = factory.GetById(_SectionId.Value);
            }
            return _Section;
        }
        set 
        {
            _SectionId = value.Id;
            _Section = value;
        }
    }

    private List<CarbonExchange.Bll.Section> _Sections;
    protected List<CarbonExchange.Bll.Section> Sections
    {
        get 
        {
            if (_Sections == null)
            {
                CarbonExchange.Bll.SectionFactory factory = new CarbonExchange.Bll.SectionFactory();
                _Sections = factory.GetAll().ToList();
            }
            return _Sections;
        }
    }

    protected override object SaveViewState()
    {
        ViewState["SectionId"] = _SectionId;
        ViewState["UserControlPaths"] = UserControlPaths;
        return base.SaveViewState();
    }

    protected override void LoadViewState(object savedState)
    {
        base.LoadViewState(savedState);
        _SectionId = ViewState["SectionId"] as int?;
        UserControlPaths = ViewState["UserControlPaths"] as List<string>;
    }

    protected bool GetSectionCompleted(ListViewDataItem item)
    {
        var section = item.DataItem as Section;
        if (UserSections != null)
        {
            var userSection = UserSections.Find(x => x.SectionId == section.Id);
            if (userSection != null)
            {
                return userSection.Completed;
            }
        }
        return false;
    }

    protected string GetSectionValue(ListViewDataItem item)
    {
        var section = item.DataItem as Section;
        if (section == null)
        {
            int id = (int)listSections.DataKeys[item.DataItemIndex]["Id"];
            section = new CarbonExchange.Bll.SectionFactory().GetById(id);
        }
        if (UserSections != null)
        {
            var userSection = UserSections.Find(x => x.SectionId == section.Id && x.Completed);
            if (userSection != null)
            {
                return userSection.Footprint.ToString("0.## kg / CO2e");
            }
        }
        return "";
    }

    private List<UserSection> _UserSections;
    protected List<UserSection> UserSections
    {
        get 
        {
            if (_UserSections == null && Audit != null)
            {
                _UserSections = new UserSectionFactory().GetAllByAuditId(Audit.Id);
            }
            return _UserSections;
        }
    }

    private Audit _Audit;
    protected Audit Audit
    {
        get
        {
            if (_Audit == null && AcmsUser != null && AcmsUser.IsAuthenticated)
            {
                _Audit = new AuditFactory().GetCurrentForUserId(AcmsUser.User.Id);
            }
            return _Audit;
        }
    }
}
